from flask import request
from flask_restx import Resource, Namespace, fields
from app.utils.response import success_response, error_response, paginate_response
from app.utils.auth import token_required
from app.utils.validators import validate_required_fields, validate_username
from app.services.admin_service import AdminService
from app.swagger_docs import (
    success_response_model, error_response_model, pagination_response_model,
    admin_model
)

# 创建管理员命名空间
admin_ns = Namespace('admins', description='管理员管理接口')

# 定义请求模型
admin_create_model = admin_ns.model('AdminCreate', {
    'admin_name': fields.String(required=True, description='管理员名称'),
    'username': fields.String(required=True, description='用户名'),
    'password': fields.String(required=True, description='密码'),
    'email': fields.String(description='邮箱'),
    'phone': fields.String(description='手机号'),
    'role_id': fields.Integer(required=True, description='角色ID'),
    'department_id': fields.Integer(description='部门ID'),
    'status': fields.Boolean(description='状态', default=True)
})

admin_update_model = admin_ns.model('AdminUpdate', {
    'admin_name': fields.String(description='管理员名称'),
    'username': fields.String(description='用户名'),
    'email': fields.String(description='邮箱'),
    'phone': fields.String(description='手机号'),
    'role_id': fields.Integer(description='角色ID'),
    'department_id': fields.Integer(description='部门ID'),
    'status': fields.Boolean(description='状态')
})

# 定义查询参数模型
admin_query_model = admin_ns.model('AdminQuery', {
    'page': fields.Integer(description='页码', default=1),
    'per_page': fields.Integer(description='每页数量', default=10),
    'keyword': fields.String(description='搜索关键词'),
    'status': fields.Integer(description='状态筛选 (0:禁用, 1:启用)')
})

@admin_ns.route('/')
class AdminListAPI(Resource):
    """管理员列表和新增接口"""
    
    @admin_ns.doc(
        description='获取管理员列表',
        security='Bearer',
        params={
            'page': '页码',
            'per_page': '每页数量',
            'keyword': '搜索关键词',
            'status': '状态筛选'
        },
        responses={
            200: ('获取成功', pagination_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin):
        """获取管理员列表"""
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int) or request.args.get('limit', 10, type=int)
        
        # 支持多种查询参数名称
        keyword = request.args.get('keyword', '') or request.args.get('name', '') or request.args.get('username', '')
        status = request.args.get('status', type=int) or request.args.get('is_active', type=int)
        
        if status is not None:
            status = bool(status)
        
        query, page, per_page = AdminService.get_list(page, per_page, keyword, status)
        return paginate_response(query, page, per_page)
    
    @admin_ns.doc(
        description='创建新管理员',
        security='Bearer',
        responses={
            200: ('创建成功', success_response_model),
            400: ('请求参数错误', error_response_model),
            401: ('未授权', error_response_model),
            500: ('服务器错误', error_response_model)
        }
    )
    @admin_ns.expect(admin_create_model, validate=True)
    @token_required
    def post(self, current_admin):
        """创建新管理员"""
        # 验证必填字段
        is_valid, error_msg = validate_required_fields(['admin_name', 'username', 'password', 'role_id'])
        if not is_valid:
            return error_response(error_msg, 400)
        
        data = request.get_json()
        
        # 验证用户名格式
        if not validate_username(data.get('username')):
            return error_response('用户名格式不正确', 400)
        
        # 检查用户名是否已存在
        existing_admin = AdminService.get_by_username(data.get('username'))
        if existing_admin:
            return error_response('用户名已存在', 400)
        
        try:
            admin = AdminService.create(data)
            return success_response(admin.to_dict(), '创建成功')
        except Exception as e:
            return error_response(f'创建失败：{str(e)}', 500)


@admin_ns.route('/<int:admin_id>')
class AdminDetailAPI(Resource):
    """管理员详情、更新和删除接口"""
    
    @admin_ns.doc(
        description='获取管理员详情',
        security='Bearer',
        responses={
            200: ('获取成功', success_response_model),
            404: ('管理员不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin, admin_id):
        """获取管理员详情"""
        admin = AdminService.get_by_id(admin_id)
        if not admin:
            return error_response('管理员不存在', 404)
        
        return success_response(admin.to_dict())
    
    @admin_ns.doc(
        description='更新管理员信息',
        security='Bearer',
        responses={
            200: ('更新成功', success_response_model),
            400: ('请求参数错误', error_response_model),
            404: ('管理员不存在', error_response_model),
            401: ('未授权', error_response_model),
            500: ('服务器错误', error_response_model)
        }
    )
    @admin_ns.expect(admin_update_model)
    @token_required
    def put(self, current_admin, admin_id):
        """更新管理员信息"""
        admin = AdminService.get_by_id(admin_id)
        if not admin:
            return error_response('管理员不存在', 404)
        
        data = request.get_json()
        
        # 如果修改用户名，检查是否重复
        if 'username' in data and data['username'] != admin.username:
            existing_admin = AdminService.get_by_username(data.get('username'))
            if existing_admin:
                return error_response('用户名已存在', 400)
        
        try:
            updated_admin = AdminService.update(admin_id, data)
            return success_response(updated_admin.to_dict(), '更新成功')
        except Exception as e:
            return error_response(f'更新失败：{str(e)}', 500)
    
    @admin_ns.doc(
        description='删除管理员',
        security='Bearer',
        responses={
            200: ('删除成功', success_response_model),
            400: ('不能删除自己', error_response_model),
            404: ('管理员不存在', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def delete(self, current_admin, admin_id):
        """删除管理员"""
        # 不能删除自己
        if admin_id == current_admin.id:
            return error_response('不能删除自己', 400)
        
        success = AdminService.delete(admin_id)
        if not success:
            return error_response('删除失败，管理员不存在', 404)
        
        return success_response(message='删除成功')


@admin_ns.route('/options')
class AdminOptionsAPI(Resource):
    """管理员选项数据接口"""
    
    @admin_ns.doc(
        description='获取管理员选项数据（角色、部门等）',
        security='Bearer',
        params={
            'type': '选项类型 (roles: 角色选项, departments: 部门选项)'
        },
        responses={
            200: ('获取成功', success_response_model),
            400: ('选项类型无效', error_response_model),
            401: ('未授权', error_response_model)
        }
    )
    @token_required
    def get(self, current_admin):
        """获取管理员选项数据"""
        option_type = request.args.get('type')
        
        if option_type == 'roles':
            data = AdminService.get_role_options()
        elif option_type == 'departments':
            data = AdminService.get_department_options()
        else:
            return error_response('无效的选项类型', 400)
        
        return success_response(data) 